package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 一般表单都是POST提交数据,解决POST乱码
        // request.setCharacterEncoding("UTF-8");

        // 1.接收用户信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 获取用户填写的验证码
        String checkCode = request.getParameter("checkCode");

        // 校验用户填写验证码是否正确
        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute("verifyCode");
        if (!checkCode.equalsIgnoreCase(verifyCode)) {
            // 验证码不同
            request.setAttribute("errorMessage", "验证码错误");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return; // 结束这个方法,不走后面的逻辑
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 2.调用service添加
        UserService userService = new UserService();
        boolean b = userService.register(user);

        if (b) {
            // 3.注册成功，则跳转登录页面
            request.setAttribute("registerMessage", "注册成功,请登录!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else {
            // 4.注册失败，给出提示信息
            request.setAttribute("errorMessage", "注册失败!");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}
